package com.cn.qgx428.lazydiary.db

import android.content.Context
import android.database.sqlite.SQLiteDatabase

import com.cn.qgx428.lazydiary.APP
import com.cn.qgx428.lazydiary.db.bean.CBill
import com.cn.qgx428.lazydiary.db.bean.CStikyNote
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper
import com.j256.ormlite.dao.Dao
import com.j256.ormlite.stmt.query.In
import com.j256.ormlite.support.ConnectionSource
import com.j256.ormlite.table.TableUtils

import java.sql.SQLException
import java.util.HashMap


class DatabaseHelper private constructor(context: Context) : OrmLiteSqliteOpenHelper(context, TABLE_NAME, null, 3) {

    private var daos: MutableMap<String, Dao<out Any, Int>> = HashMap()

    override fun onCreate(database: SQLiteDatabase,
                          connectionSource: ConnectionSource) {
        TableUtils.createTable(connectionSource, CStikyNote::class.java)
        TableUtils.createTable(connectionSource, CBill::class.java)
    }

    override fun onUpgrade(database: SQLiteDatabase,
                           connectionSource: ConnectionSource, oldVersion: Int, newVersion: Int) {
        //暂时没发解决升级问题
        TableUtils.dropTable<CStikyNote, Int>(connectionSource, CStikyNote::class.java,true)
        TableUtils.dropTable<CBill, In>(connectionSource, CBill::class.java, true)
        onCreate(database, connectionSource)
    }

    @Synchronized
    fun newDao(clazz: Class<*>): Dao< out Any, Int> {
        var dao: Dao<*, Int>? = null
        val className = clazz.simpleName

        if (daos.containsKey(className)) {
            dao = daos.get(className)
        }
        if (dao == null) {
            dao = super.getDao(clazz) as Dao< Any, Int>
            daos.put(className, dao)
        }
        return dao
    }

    /**
     * 释放资源
     */
    override fun close() {
        super.close()
        for (key in daos.keys) {
            var dao: Dao<*, *>? = daos[key]
            dao = null
        }
    }

    companion object {
        private val TABLE_NAME = "lazyDiary.db"

         object Inner{
            public val instance: DatabaseHelper = DatabaseHelper(APP.getAppContext())
        }

       fun newInstance(): DatabaseHelper  {
           return Inner.instance
       }
    }

}
